package com.stockz.ui.swing.charting.widget;

import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Iterator;

import com.stockz.ui.swing.charting.model.Shape;
import com.stockz.ui.swing.charting.util.RepaintStockChartPanelUtil;
import com.stockz.ui.swing.charting.view.StockChartPanel;
import com.stockz.ui.swing.widget.JButton;

public class RedoDrawingButton extends JButton implements ActionListener{
	private static final long serialVersionUID = 1994801430449290993L;
	
	private final StockChartPanel stockChartPanel;
	
	public RedoDrawingButton(StockChartPanel stockChartPanel){
		super("Redo","redo.png");
		this.stockChartPanel = stockChartPanel;
		addActionListener(this);
		Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener(){
		    public void eventDispatched(AWTEvent e){
		    	if(e instanceof KeyEvent){
		    		KeyEvent keyEvent = (KeyEvent)e;
			       if(!keyEvent.isConsumed() && keyEvent.getID() == KeyEvent.KEY_RELEASED 
			    		   &&  keyEvent.getKeyCode() == KeyEvent.VK_Y && keyEvent.isControlDown()){
			    	   keyEvent.consume();
			    	   actionPerformed(null);
			       }
		    	}
		    }
		}, AWTEvent.KEY_EVENT_MASK);
	}
	
	@Override
	public void actionPerformed(ActionEvent event) {
		if(stockChartPanel != null){
			Iterator<Shape> iterator = stockChartPanel.getStockChartPanelState().getShapeSet().iterator();
			Shape shape = null;
			Shape targetShape = null;
			while(iterator.hasNext()){
				shape = iterator.next();
				if(!shape.isVisible()){
					targetShape = shape;
					break;
				}
			}
			if(targetShape != null){
				targetShape.setVisible(true);
				RepaintStockChartPanelUtil.repaintStockChartPanel(stockChartPanel);
			}
		}
	}
}
